//
//  BXSProtocolMediator.m
//  BXSProtocolMediator
//
//  Created by 金申生 on 2017/3/1.
//  Copyright © 2017年 Hangzhou WeiEase Tech Co., Ltd. All rights reserved.
//

#import "BXSProtocolMediator.h"

@interface BXSProtocolMediator ()

@property (nonatomic, strong) NSMutableDictionary *impCache;

@property (nonatomic, strong) dispatch_semaphore_t lock;

@end

@implementation BXSProtocolMediator

- (instancetype)init
{
    if (self = [super init]) {
        self.impCache = [NSMutableDictionary dictionaryWithCapacity:10];
        self.lock = dispatch_semaphore_create(1);
    }
    
    return self;
}

+ (instancetype)sharedInstance
{
    static BXSProtocolMediator *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BXSProtocolMediator alloc] init];
    });
    
    return instance;
}

- (id)impForProtocol:(Protocol *)protocol
{
    id obj = nil;
    
    dispatch_semaphore_wait(self.lock, DISPATCH_TIME_FOREVER);
    
    obj = [self.impCache objectForKey:NSStringFromProtocol(protocol)];
    
    dispatch_semaphore_signal(self.lock);
    
    return obj;
}

- (void)setImp:(id)imp forProtocol:(Protocol *)protocol
{
    dispatch_semaphore_wait(self.lock, DISPATCH_TIME_FOREVER);
    
    [self.impCache setObject:imp forKey:NSStringFromProtocol(protocol)];
    
    dispatch_semaphore_signal(self.lock);
}

@end




id impForProtocol(Protocol *protocol)
{
    return [[BXSProtocolMediator sharedInstance] impForProtocol:protocol];
}
